﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace King.Engine.Core
{

    /// <summary>
    /// Manager that contains the current activity.
    /// </summary>
    public static class ActivityManager
    {

        #region Fields

        private static Activity _currentActivity;
        private static Activity _nextActivity;
        private static Action<GameTime> _update;

        #endregion


        #region Properties

        /// <summary>
        /// Get the current Activity
        /// </summary>
        public static Activity CurrentActivity
        {
            get
            {
                return _currentActivity;
            }
        }

        #endregion
        

        #region Constructor

        static ActivityManager()
        {
            _update = UpdateNewActivity;
        }

        #endregion


        #region Public Methods

        /// <summary>
        /// Set the current activity. This will be performed at the start of the next Update.
        /// </summary>
        public static void SetActivity(Activity activity)
        {
            _nextActivity = activity;
            _update = (activity.IsNew) ? (Action<GameTime>) UpdateNewActivity : UpdateResumedActivity;
        }

        /// <summary>
        /// Set the current activity to a new activity of the given type. 
        /// This will be performed at the start of the next Update.
        /// </summary>
        public static void SetActivity<T>() where T:Activity, new()
        {
            SetActivity(new T());
        }

        #endregion


        #region Internal Methods

        internal static void Update(GameTime gameTime)
        {
            _update(gameTime);
        }

        internal static void Draw()
        {
            _currentActivity.Draw();
        }

        #endregion


        #region Private Methods

        private static void UpdateNewActivity(GameTime gameTime)
        {
            _currentActivity = _nextActivity;
            _currentActivity.OnStart();
            _currentActivity.OnResume();
            
            _update = UpdateActivity;
            UpdateActivity(gameTime);
        }

        private static void UpdateResumedActivity(GameTime gameTime)
        {
            _currentActivity = _nextActivity;
            _currentActivity.OnResume();

            _update = UpdateActivity;
            UpdateActivity(gameTime);
        }

        private static void UpdateActivity(GameTime gameTime)
        {
            _currentActivity.Update(gameTime);
        }

        #endregion

    }
}
